package com.jichaoyun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.jichaoyun.common.enums.ChargeStatus;
import com.jichaoyun.common.enums.ChargeType;
import com.jichaoyun.common.enums.MyExceptiontType;
import com.jichaoyun.common.ex.MyException;
import com.jichaoyun.common.model.PagedResult;
import com.jichaoyun.common.model.Result;
import com.jichaoyun.model.entity.Rechargeinfo;
import com.jichaoyun.model.entity.StationInfo;
import com.jichaoyun.model.entity.User;
import com.jichaoyun.model.vo.ChargeBankVo;
import com.jichaoyun.model.vo.PriceChangeModel;
import com.jichaoyun.model.vo.SettlementAdjustModel;
import com.jichaoyun.service.*;
import com.jichaoyun.util.EncodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhen
 */

@RestController
@Api(tags = {"充值管理列表"})
@RequestMapping("/sys/charge")
@Slf4j
public class ChargeController {

    @Autowired
    private IStationInfoService stationInfoService;

    @Autowired
    private IRechargeinfoService rechargeinfoService;

    @Autowired
    private IBalanceAlarmService balancealarmService;

    @Autowired
    private IPriceChangeService priceChangeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ComPortService comPortService;

    @ApiOperation(value = "根据站点名称获取电话号码")
    @GetMapping("/getTelByStationName")
    public Result<String> getTelByStationName(String stationName) {

        return Result.success(stationInfoService.getTelByStationName(stationName));

    }

    @ApiOperation(value = "充值记录查询，默认查询全部的充值记录", notes = "默认是和上月的同日进行对比")
    @GetMapping("/selectTotalCharge")
    public Result<Map<String, Object>> selectTotalCharge() {
        HashMap<String, Object> resMap = new HashMap<>();
        BigDecimal totalReCharge = rechargeinfoService.getTotalReCharge();
        resMap.put("总充值金额", totalReCharge);
        Integer totalIC = rechargeinfoService.getTotalIcReCharge();
        resMap.put("充值IC卡笔数", totalIC);
        Integer totalSys = rechargeinfoService.getTotalSysReCharge();
        resMap.put("银行转账笔数", totalSys);
        Integer totalAux = rechargeinfoService.getTotalAuxReCharge();
        resMap.put("辅助充值笔数", totalAux);

        Integer year = LocalDateTime.now().getYear();
        Integer month = LocalDateTime.now().getMonthValue();

        String totalReChargeRate = rechargeinfoService.getTotalReChargeRate(year, month);
        resMap.put("总充值金额变化率", totalReChargeRate);

        String ICReChargeRate = rechargeinfoService.getICReChargeRate(year, month);
        resMap.put("充值IC卡变化率", ICReChargeRate);

        String sysReChargeRate = rechargeinfoService.getSysReChargeRate(year, month);
        resMap.put("银行转账变化率", sysReChargeRate);

        String auxReChargeRate = rechargeinfoService.getAuxReChargeRate(year, month);
        resMap.put("辅助充值变化率", auxReChargeRate);

        return Result.success(resMap);
    }


    @ApiOperation("充值记录查询，查询全部用户某年某月的充值记录")
    @GetMapping("/selectChargeByMonth")
    public Result<Map<String, Object>> selectChargeByMonth(Integer year, Integer month) {
        HashMap<String, Object> resMap = new HashMap<>();
        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);


        BigDecimal totalReCharge = rechargeinfoService.getTotalReChargeByMonth(start, end);
        resMap.put("总充值金额", totalReCharge);
        Integer totalIC = rechargeinfoService.getTotalIcReChargeByMonth(start, end);
        resMap.put("充值IC卡笔数", totalIC);
        Integer totalSys = rechargeinfoService.getTotalSysReChargeByMonth(start, end);
        resMap.put("银行转账笔数", totalSys);
        Integer totalAux = rechargeinfoService.getTotalAuxReChargeByMonth(start, end);
        resMap.put("辅助充值笔数", totalAux);

        String totalReChargeRate = rechargeinfoService.getTotalReChargeRate(year, month);
        resMap.put("总充值金额变化率", totalReChargeRate);

        String ICReChargeRate = rechargeinfoService.getICReChargeRate(year, month);
        resMap.put("充值IC卡变化率", ICReChargeRate);

        String sysReChargeRate = rechargeinfoService.getSysReChargeRate(year, month);
        resMap.put("银行转账变化率", sysReChargeRate);

        String auxReChargeRate = rechargeinfoService.getAuxReChargeRate(year, month);
        resMap.put("辅助充值变化率", auxReChargeRate);

        return Result.success(resMap);
    }

    @ApiOperation("充值记录查询，查询某个用户某年某月的充值记录")
    @GetMapping("/selectChargeByMonthAndStation")
    public Result<Map<String, Object>> selectChargeByMonthAndStation(Integer stationNo, Integer year, Integer month) {
        HashMap<String, Object> resMap = new HashMap<>();
        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);


        BigDecimal totalReCharge = rechargeinfoService.getTotalReChargeByMonthAndStation(stationNo, start, end);
        resMap.put("总充值金额", totalReCharge);
        Integer totalIC = rechargeinfoService.getTotalIcReChargeByMonthAndStation(stationNo, start, end);
        resMap.put("充值IC卡笔数", totalIC);
        Integer totalSys = rechargeinfoService.getTotalSysReChargeByMonthAndStation(stationNo, start, end);
        resMap.put("银行转账笔数", totalSys);
        Integer totalAux = rechargeinfoService.getTotalAuxReChargeByMonthAndStation(stationNo, start, end);
        resMap.put("辅助充值笔数", totalAux);
        return Result.success(resMap);
    }

    @ApiOperation("充值趋势分析，查询某个用户某年某月每天的充值记录")
    @GetMapping("/selectChargeListByMonthAndStation")
    public Result<Map<String, Map<String, Object>>> selectChargeListByMonthAndStation(Integer stationNo, Integer year, Integer month) {

        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);

        Map<String, Map<String, Object>> resMap = rechargeinfoService.selectChargeListByMonthAndStation(stationNo, start, end);

        return Result.success(resMap);
    }


    @ApiOperation("充值趋势分析，查询所有用户某年某月每天的充值记录")
    @GetMapping("/selectAllChargeListByMonth")
    public Result<Map<String, Map<String, Object>>> selectAllChargeListByMonth(Integer year, Integer month) {

        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);

        Map<String, Map<String, Object>> resMap = rechargeinfoService.selectAllChargeListByMonth(start, end);

        return Result.success(resMap);
    }

    @ApiOperation("充值渠道分析，所有的用户,所有的时间")
    @GetMapping("/selectAllChargeWay")
    public Result<Map<String, Object>> selectAllChargeWay() {

        Map<String, Object> resMap = rechargeinfoService.selectAllChargeWay();

        return Result.success(resMap);
    }


    @ApiOperation("充值渠道分析，所有的用户,某年某月")
    @GetMapping("/selectAllChargeWayByMonth")
    public Result<Map<String, Object>> selectAllChargeWayByMonth(Integer year, Integer month) {
        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);
        Map<String, Object> resMap = rechargeinfoService.selectAllChargeWayByMonth(start, end);

        return Result.success(resMap);
    }

    @ApiOperation("充值渠道分析，某个用户,某年某月")
    @GetMapping("/selectAllChargeWayByMonthAndStation")
    public Result<Map<String, Object>> selectAllChargeWayByMonthAndStation(Integer stationNo, Integer year, Integer month) {

        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);

        Map<String, Object> resMap = rechargeinfoService.selectAllChargeWayByMonthAndStation(stationNo, start, end);

        return Result.success(resMap);
    }


    @ApiOperation("充值用户的记录，分页查询，全部用户")
    @GetMapping("/selectAllChargeInfoListByPage")
    public Result<PagedResult> selectAllChargeInfoListByPage(Integer pageNo) {
        PagedResult pagedResult = rechargeinfoService.selectAllChargeInfoListByPage(pageNo);

        return Result.success(pagedResult);
    }


    @ApiOperation("充值用户的记录，分页查询，某个用户")
    @GetMapping("/selectAllChargeInfoListByPageAndStaion")
    public Result<PagedResult> selectAllChargeInfoListByPageAndStaion(Integer pageNo, Integer stationNo) {
        PagedResult pagedResult = rechargeinfoService.selectAllChargeInfoListByPageAndStaion(pageNo, stationNo);

        return Result.success(pagedResult);
    }

    @ApiOperation("余额报警用户占比，所有的用户, 默认所有的时间")
    @GetMapping("/selectBalanceAlarmCountALL")
    public Result<Map<String, Object>> selectBalanceAlarmCountALL() {

        Map<String, Object> resMap = balancealarmService.selectBalanceAlarmCountALL();

        return Result.success(resMap);
    }


    @ApiOperation("余额报警用户占比，所有的用户, 某年某月")
    @GetMapping("/selectBalanceAlarmCountByMonth")
    public Result<Map<String, Object>> selectBalanceAlarmCountByMonth(Integer year, Integer month) {
        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);

        Map<String, Object> resMap = balancealarmService.selectBalanceAlarmCountByMonth(start, end);

        return Result.success(resMap);
    }

    @ApiOperation("余额报警用户趋势，全部路线, 某年某月")
    @GetMapping("/selectBalanceAlarmListByMonth")
    public Result<Map<String, Object>> selectBalanceAlarmListByMonth(Integer year, Integer month) {
        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);

        Map<String, Object> resMap = balancealarmService.selectBalanceAlarmListByMonth(start, end);

        return Result.success(resMap);
    }

    @ApiOperation("余额报警用户趋势，某个路线, 某年某月")
    @GetMapping("/selectBalanceAlarmListByMonthAndLine")
    public Result<Map<String, Object>> selectBalanceAlarmListByMonthAndLine(Integer lineId, Integer year, Integer month) {
        LocalDateTime start = LocalDateTime.of(year, month, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(year, month, 1, 0, 0, 0).plusMonths(1);

        Map<String, Object> resMap = balancealarmService.selectBalanceAlarmListByMonthAndLine(lineId, start, end);

        return Result.success(resMap);
    }

    @ApiOperation("余额报警用户，分页查询，全部线路，所有月份")
    @GetMapping("/selectAllBalanceAlarmListByPage")
    public Result<PagedResult> selectAllBalanceAlarmListByPage(Integer pageNo) {
        PagedResult pagedResult = balancealarmService.selectAllBalanceAlarmListByPage(pageNo);

        return Result.success(pagedResult);
    }

    @ApiOperation("余额报警用户，分页查询，某个线路，所有月份")
    @GetMapping("/selectAllBalanceAlarmListByPageAndLine")
    public Result<PagedResult> selectAllBalanceAlarmListByPageAndLine(Integer lineId, Integer pageNo) {
        PagedResult pagedResult = balancealarmService.selectAllBalanceAlarmListByPageAndLine(lineId, pageNo);

        return Result.success(pagedResult);
    }

    @ApiOperation("汽费记录，分页查询，全部修改")
    @GetMapping("/selectPriceChangeListByPage")
    public Result<PagedResult> selectPriceChangeListByPage(Integer pageNo) {
        PagedResult pagedResult = priceChangeService.selectPriceChangeListByPage(pageNo);
        return Result.success(pagedResult);
    }

//    @ApiOperation("辅助充值")
//    @PostMapping("/rechargeAssisted")
//    public Result<?> rechargeAssisted(Integer stationId,
//        BigDecimal num,
//        String username,
//        String password) throws Exception {
//        User loginEntity = userService.login(username,password);
//        StationInfo result = stationInfoService.getById(stationId);
//        if(result == null){
//            throw new MyException(MyExceptiontType.STATIONNOTFIND,null);
//        }
//        if(loginEntity != null){
//            Rechargeinfo info = new Rechargeinfo();
//            info.setReChargeValue(num);
//            info.setChargeType(ChargeType.ASSIST.getCnName());
//            LocalDateTime now = LocalDateTime.now();
//            LocalDateTime datetime = LocalDateTime.of(now.toLocalDate(),now.toLocalTime().withNano(0));
//            info.setTime(datetime);
//            info.setIsRead(false);
//            info.setStationNo(stationId);
//            info.setStationName(result.getStationName());
//            StringBuilder remark = new StringBuilder(result.getStationName());
//            remark.append("辅助充值").append(num.toString()).append("元");
//            info.setRemark(remark.toString());
//            rechargeinfoService.save(info);
//            Rechargeinfo rechargeinfo = rechargeinfoService.getById(info.getId());
//            try{
//                priceChangeService.recharge(rechargeinfo);
//            }catch (MyException e){
//                rechargeinfoService.removeById(info.getId());
//                return Result.resultError(e);
//            }
//            return Result.success(info.getStationName()+"充值成功");
//        }else {
//            return Result.resultError(new MyException(MyExceptiontType.PASSWORDNOTMATCH,"密码错误"));
//        }
//    }
    @ApiOperation("预充值-财务发起预充值")
    @PostMapping("/initiateChargeRequest")
    public Result<?> initiateChargeRequest(Integer stationId,
                                      BigDecimal num,
                                      String username,
                                      String password, String remark) throws Exception {
        User loginEntity = userService.login(username,password);
        StationInfo result = stationInfoService.getById(stationId);
        if(result == null){
            throw new MyException(MyExceptiontType.STATIONNOTFIND,null);
        }
        if(loginEntity != null) {
            Rechargeinfo info = new Rechargeinfo();
            info.setReChargeValue(num);
            info.setChargeType(ChargeType.ASSIST.getCnName());
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime datetime = LocalDateTime.of(now.toLocalDate(), now.toLocalTime().withNano(0));
            info.setTime(datetime);
            info.setIsRead(false);
            info.setStationNo(stationId);
            info.setStationName(result.getStationName());
            if(remark.isEmpty()){
                StringBuilder newRemark = new StringBuilder(result.getStationName());
                newRemark.append("预充值").append(num.toString()).append("元");
                info.setRemark(newRemark.toString());
            }else {
                info.setRemark(remark);
            }
            //使用status表示当前状态
            info.setStatus(ChargeStatus.FINANCE_OFFERED.getStatus());
            rechargeinfoService.save(info);
            Rechargeinfo rechargeinfo = rechargeinfoService.getById(info.getId());
            return Result.success(rechargeinfo);
//            try{
//                priceChangeService.recharge(rechargeinfo);
//            }catch (MyException e){
//                rechargeinfoService.removeById(info.getId());
//                return Result.resultError(e);
//            }
//            return Result.success(info.getStationName()+ChargeStatus.FINANCE_OFFERED.getMsg()+"充值成功");
        }else {
            return Result.resultError(new MyException(MyExceptiontType.PASSWORDNOTMATCH,"密码错误"));
        }
    }


        @ApiOperation("预充值-热网办公室进行审核")
        @PostMapping("/executeCharge")
        public Result<?> executeCharge(Integer id,String username, String password) throws Exception {
            User loginEntity = userService.login(username,password);
            if(loginEntity != null){
                //根据id找到info
                Rechargeinfo info = rechargeinfoService.getById(id);
                if(Objects.isNull(info)){
                    return Result.resultError(new MyException(MyExceptiontType.RECHARGEISNULL,null));
                }
                //使用status表示当前状态
                if(!info.getStatus().equals(ChargeStatus.FINANCE_OFFERED.getStatus())){
                    return Result.resultError(new MyException(MyExceptiontType.RECHARGE_STATUS_ERR,null));
                }
                //更新时间
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime datetime = LocalDateTime.of(now.toLocalDate(), now.toLocalTime().withNano(0));
                info.setTime(datetime);
                //更新状态
                info.setStatus(ChargeStatus.OFFICIAL_RECEIVED.getStatus());
                rechargeinfoService.updateById(info);
                return Result.success(info.getStationName()+ChargeStatus.OFFICIAL_RECEIVED.getMsg()+"成功");
            }else {
                return Result.resultError(new MyException(MyExceptiontType.PASSWORDNOTMATCH,"密码错误"));
            }
        }

    @ApiOperation("预充值-经理进行审批")
    @PostMapping("/confirmCharge")
    public Result<?> confirmCharge(Integer id,String username, String password) throws Exception {
        User loginEntity = userService.login(username,password);
        if(loginEntity != null){
            //根据id找到info 确认当前状态为1，修改状态为2
            Rechargeinfo info = rechargeinfoService.getById(id);
            if(Objects.isNull(info)){
                return Result.resultError(new MyException(MyExceptiontType.RECHARGEISNULL,null));
            }
            //使用status表示当前状态
            if((!info.getStatus().equals(ChargeStatus.OFFICIAL_RECEIVED.getStatus())) && (!info.getStatus().equals(ChargeStatus.REAL_CARD_FAILED.getStatus()))){
                return Result.resultError(new MyException(MyExceptiontType.RECHARGE_STATUS_ERR,null));
            }
            //更新时间
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime datetime = LocalDateTime.of(now.toLocalDate(), now.toLocalTime().withNano(0));
            info.setTime(datetime);
            //更新状态
            info.setStatus(ChargeStatus.MANAGER_RECEIVED.getStatus());
//            rechargeinfoService.updateById(info);
            //写入到mc2000中
            try{
                priceChangeService.recharge(info);
            }catch (MyException e){
                info.setStatus(ChargeStatus.REAL_CARD_FAILED.getStatus());
                rechargeinfoService.updateById(info);
                return Result.resultError(new MyException(MyExceptiontType.STATIONOUTLINE,"MC2000充值失败"));
            }
            return Result.success(info.getStationName()+ChargeStatus.MANAGER_RECEIVED.getMsg()+"成功");
        }else {
            return Result.resultError(new MyException(MyExceptiontType.PASSWORDNOTMATCH,"密码错误"));
        }
    }

    @ApiOperation("预充值-取消充值")
    @PostMapping("/cancelCharge")
    public Result<?> cancelCharge(Integer id,String username, String password,String remark) throws Exception {
        User loginEntity = userService.login(username,password);
        if(Objects.isNull(loginEntity)){
            return Result.resultError(new MyException(MyExceptiontType.PASSWORDNOTMATCH,"密码错误"));
        }
        Rechargeinfo info = rechargeinfoService.getById(id);
        if(Objects.isNull(info)){
            return Result.resultError(new MyException(MyExceptiontType.RECHARGEISNULL,null));
        }
        //将状态置为取消
        info.setStatus(ChargeStatus.CANCELLED.getStatus());
        info.setRemark(remark);
        info.setTime(LocalDateTime.now());
        rechargeinfoService.updateById(info);
        return Result.success("取消成功");
    }

    @ApiOperation("查询预充值记录")
    @GetMapping("/getChargeFlowList")
    public Result<PagedResult> getChargeFlowList(Integer pageNo){
        PagedResult pagedResult = rechargeinfoService.selectAllChargeInfoListByPage(pageNo);
        return Result.success(pagedResult);
    }
    @GetMapping("/updateReadStatus")
    public Result<?> updateReadStatus(Integer id){
        Rechargeinfo rechargeinfo = rechargeinfoService.getById(id);
        if(Objects.isNull(rechargeinfo)){
            return Result.resultError(new MyException(MyExceptiontType.RECHARGEISNULL,null));
        }
        rechargeinfo.setIsRead(true);
        rechargeinfoService.updateById(rechargeinfo);
        return Result.success(rechargeinfo);
    }

    @ApiOperation("根据id查询预充值信息")
    @GetMapping("/getChargeFlowDetail")
    public Result<Rechargeinfo> getChargeFlowDetail(Integer id){
        Rechargeinfo rechargeinfo = rechargeinfoService.getById(id);
        return Result.success(rechargeinfo);
    }


    @ApiOperation("银行充值")
    @PostMapping("/rechargeBank")
    public Result<ChargeBankVo> chargeBank(
        @RequestBody Map<String, Object> data) throws Exception {
        ChargeBankVo chargeVo = EncodeUtil.decode_jichao(data);
        log.info("收到一条银行流水： "+chargeVo.toString());
        Rechargeinfo info = new Rechargeinfo();
        info.setReChargeValue(BigDecimal.valueOf(chargeVo.getAmount()));
        info.setChargeType(ChargeType.BANK.getCnName());
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime datetime = LocalDateTime.of(now.toLocalDate(),now.toLocalTime().withNano(0));
        info.setTime(datetime);
        info.setIsRead(false);
        LambdaQueryWrapper<StationInfo> wrapper = new LambdaQueryWrapper<>();
        List<StationInfo> lists = null;
        if(chargeVo.getReversal()){
            //如果是冲正流水，把付款方对应站点的误冲的余额扣除
            wrapper.eq(StationInfo::getBankCardNumber,chargeVo.getSend_id());
            lists= stationInfoService.getBaseMapper().selectList(wrapper);

        }else{
            wrapper.eq(StationInfo::getBankCardNumber,chargeVo.getReceive_id());
            lists = stationInfoService.getBaseMapper().selectList(wrapper);
        }
        if(lists.size()==0){
            throw new MyException(MyExceptiontType.Other,"非指定银行账号");
        }
        StationInfo station = lists.get(0);
        info.setStationNo(station.getStationNo());
        info.setStationName(station.getStationName());
        StringBuilder remark = new StringBuilder(station.getStationName());
        remark.append("银行充值").append(chargeVo.getAmount().toString()).append("元");
        info.setRemark(remark.toString());
        rechargeinfoService.save(info);
        return Result.success(chargeVo);
    }



    @ApiOperation("启动汽费调整")
    @PostMapping("/startPriceChange")
    public Result<?> startPriceChage(@RequestBody PriceChangeModel model) {
        priceChangeService.startPriceChange(model);
        return Result.success();
    }

    @ApiOperation("批量启用汽费调整")
    @PostMapping("/batchStartPriceChange")
    public Result<?> StartPriceChage(@RequestBody List<PriceChangeModel> models) {
        priceChangeService.startPriceChange(models);
        return Result.success();
    }

    @ApiOperation("结算调整,列表显示两个时间段站点信息和站点总量")
    @PostMapping("/settlementAdjust")
    public Result<PagedResult> settlementAdjust(@RequestBody SettlementAdjustModel model) {
        PagedResult pagedResult = priceChangeService.selectTotalBetween(model.getPageNo(),model.getStartTime(),model.getEndTime());
        return Result.success(pagedResult);
    }

    @ApiOperation("IC卡充值,空闲串口号查询")
    @GetMapping("/findPort")
    public Result<?> findPort() {
        return Result.success(comPortService.findPort());
    }

    @ApiOperation("IC卡充值,打开串口")
    @GetMapping("/openPort")
    public Result<?> openPort(Integer userId,String portName) {
        comPortService.openPort(userId,portName,115200,8,0,1);
        return Result.success();
    }

    @ApiOperation("IC卡充值,连接读卡器")
    @GetMapping("/ConnectCardRead")
    public Result<String> ConnectCardRead(Integer userId) throws InterruptedException {
        return Result.success(comPortService.ConnectCardRead(userId));
    }

    @ApiOperation("IC卡充值,读取卡号")
    @GetMapping("/readCardNum")
    public Result<String> readCardNum(Integer userId) throws InterruptedException {
        return Result.success(comPortService.readCardNum(userId));
    }


    @ApiOperation("IC卡充值,查询所有未绑定IC卡的用户")
    @GetMapping("/selectNoICCardStation")
    public Result<?> selectNoICCardStation(){
        return Result.success(comPortService.findNoICStation());
    }

    @ApiOperation("IC卡充值,查询所有已绑定IC卡的用户")
    @GetMapping("/selectHadICCardStation")
    public Result<?> selectHadICCardStation(){
        return Result.success(comPortService.findHadICStation());
    }

    @ApiOperation("IC卡充值,绑定IC卡")
    @PostMapping("/bindingICCard")
    public Result<?> bindingICCard(String stationName,String ICCardNum){
        comPortService.bindingIcCard(stationName,ICCardNum);
        return Result.success("绑定成功");
    }

    @ApiOperation("IC卡充值,补发绑定IC卡")
    @PostMapping("/bindingBoundIcCard")
    public Result<?> bindingBoundIcCard(String ICCardNum){
        comPortService.bindingBoundIcCard(ICCardNum);
        return Result.success("绑定成功");
    }

    @ApiOperation("IC卡充值,根据IC卡号返回站点名称")
    @GetMapping("/getStationNameByIcCard")
    public Result<?> getStationNameByIcCard(String ICCardNum){
        return Result.success(comPortService.getStationNameByIcCard(ICCardNum));
    }

    @ApiOperation("IC卡充值,充值IC卡")
    @PostMapping("/rechargeICCard")
    public Result<?> rechargeICCard(Integer userId,Float number) throws InterruptedException {
        return Result.success(comPortService.reChargeIcCard(userId,number));
    }

    @ApiOperation("（外部api）,获取各个用户的当日累计充值和当天的消费")
    @GetMapping("/getAccSpendByUsers")
    public Result<List<Map<String,Float>>> getAccSpendByUsers(){
        List<Map<String, Float>> resList = new ArrayList<>();
        //获取当日充值信息
        List<Map<String, Object>> rechargelist = rechargeinfoService.getAccRechargeByUsers();
        HashMap<String, Float> rechargeMap = new HashMap<>();
        for (Map<String, Object> map : rechargelist) {
            rechargeMap.put((String) map.get("station_name"), ((BigDecimal) map.get("acc_charge")).floatValue());
        }
        resList.add(rechargeMap);

        //获取当日消费信息
        resList.add(rechargeinfoService.getAccSpendByUsers());

        return Result.success(resList);
    }
}
